package com.itstyle.quartz.kettleUtil;

import com.itstyle.quartz.job.kettleJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author ycj
 * @version 1.0
 * @description
 * @date 2020/10/21 14:40
 */
public class FileReadUtil {
    private static final Logger logger = LoggerFactory.getLogger(kettleJob.class);


    // 读取指定路径文本文件
    public static HashMap<String, List<String>> read(String filePath) {

        int index1 = 0;
        int index2 = 0;
        int index3 = 0;
        int index4 = 0;

        String tablevalue = "";
        String fieldvalue = "";
        String values = "";

        StringBuilder str = new StringBuilder();

        List<String> value = new ArrayList<>();
        List<String> field = new ArrayList<>();
        List<String> table = new ArrayList<>();
        List<String> nulltable = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();

        BufferedReader in = null;
        int i = 0;

        String[] split = filePath.split("\\.");
        String type = split[1];

        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "GBK");
//            InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "UTF-8");
            in = new BufferedReader(isr);
            String s;
            try {
                while ((s = in.readLine()) != null) {
                    if (s.contains("<Compensator_S") && !filePath.contains("青海") || s.contains("<Converter") && !filePath.contains("青海") || s.contains("<DCline")) {
                        index1++;
                        continue;
                    }

                    if (type.equals("DT") && s.contains("<RectifierInverter") || type.equals("DT") &&  s.contains("<DCLineDot")) {
                        index2++;
                        continue;
                    }

                    if (type.equals("CIME") && s.contains("<DCLineSegment")
                            || type.equals("CIME") && s.contains("<DCLineDot")
                            || type.equals("CIME") && s.contains("<Dcsmoothingreactor")
                            || type.equals("CIME") && s.contains("<Dcfilter")
                            || type.equals("CIME") && s.contains("<RectifierInverter") && !filePath.contains("00_28")
                            || type.equals("CIME") && s.contains("<SeriesCompensator")  && !filePath.contains("00_28") && !filePath.contains("01_28")) {
                        index3++;
                        continue;
                    }

                    if (index2==1) {
                        continue;
                    }else if (index2==2) {
                        index2=0;
                        continue;
                    }

                    if (index3==1) {
                        index3++;
                        continue;
                    }else if (index3==2) {
                        index3++;
                        continue;
                    }else if (index3==3) {
                        index3=0;
                        continue;
                    }

                    if (index1==1) {
                        index1++;
                        continue;
                    }else if (index1==2) {
                        index1++;
                        continue;
                    }else if (index1==3) {
                        index1=0;
                        continue;
                    }

                    str.append(s + '\n');
                    if (s.equals("")) {
                        continue;
                    }
                    if (s.charAt(0)=='#') {
                        value.add(s);
                    }else if (s.charAt(0)=='<') {
                        if (!s.contains("!")) {
                            if (!s.contains("/")) {
                                table.add(s);
                            }
                        }
                    }else if (s.charAt(0)=='@') {
                        field.add(s);
                    }
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        map.put("value",value);
        map.put("field",field);
        map.put("table",table);

        return map;
    }

    // 读取指定路径DT文本文件
    public static HashMap<String, List<String>> readDT(String filePath) {

        StringBuilder str = new StringBuilder();


        List<String> value = new ArrayList<>();
        HashMap<String, List<String>> map = new HashMap<>();

        BufferedReader in = null;
        int i = 0;

        String[] split = filePath.split("\\.");
        String type = split[1];

        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "GBK");
            in = new BufferedReader(isr);
            String s;
            try {
                while ((s = in.readLine()) != null) {

                    str.append(s + '\n');
                    if (s.equals("")) {
                        continue;
                    }
                    value.add(s);
                }
            } finally {
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
        map.put("value",value);

        return map;
    }

    //读取指定文件夹下所有文件
    public static File[] getFile(String path) {
        // get file list where the path has
        File file = new File(path);
        // get the folder list
        File[] array = file.listFiles();

        for (int i = 0; i < array.length; i++) {
            if (array[i].isFile()) {
                // only take file name
//                System.out.println("^^^^^" + array[i].getName());
            } else if (array[i].isDirectory()) {
                getFile(array[i].getPath());
            }
        }
//        System.out.println("文件夹下有"+array.length+"个文件");
        return array;
    }

    /**
    * //1.从旧文件拷贝内容到新文件
    * //2.删除旧文件
    * @param oldPath the path+name of old file
    * @param newPath the path+name of new file
    * @throws Exception
    */
    public static void transferFile(String oldPath, String newPath) {
        int byteread = 0;
        File oldFile = new File(oldPath);
        File newFile = new File(newPath);

        FileInputStream fin = null;
        FileOutputStream fout = null;
        try {
            if (oldFile.exists()) {
                fin = new FileInputStream(oldFile);
                fout = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                while ((byteread = fin.read(buffer)) != -1) {
                    logger.debug("byteread==" + byteread);
                    fout.write(buffer, 0, byteread);
                }
                if (fin != null) {
                    fin.close();//如果流不关闭,则删除不了旧文件
                    fout.close();
                    delFile(oldFile);
                }
            } else {
                logger.error("需要转移的文件不存在!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("转移文件异常");
        } finally {
            if (fin != null) {
                try {
                    fin.close();
                    fout.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    logger.error("流关闭异常");
                }
            }
        }
    }

    /**
     　　* 删除文件,只支持删除文件,不支持删除目录
     　　* @param file
     　　* @throws Exception
     　　*/
    public static void delFile(File file){
        try {
            if (!file.exists()) {
                logger.error("文件" + file.getName() + "不存在,请确认!");
            }
            if (file.isFile()) {
                if (file.canWrite()) {
                    file.delete();
                } else {
                    logger.error("文件" + file.getName() + "只读,无法删除,请手动删除!");
                }
            } else {
                logger.error("文件" + file.getName() + "不是一个标准的文件,有可能为目录,请确认!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除文件异常");
        }
    }
}
